package com.demo.mq.activemq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;

import javax.jms.*;

/**
 * 消息消费者
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/13 17:00
 */
public class ConsumerDemo {

    private static final String URL = "tcp://192.168.28.130:61616";

    public static void consumerQueue(){
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,URL);
        Connection connection = null;

        try {
            connection = connectionFactory.createConnection();
            connection.start();
            ActiveMQSession session = (ActiveMQSession) connection.createSession(Boolean.TRUE,Session.CLIENT_ACKNOWLEDGE);
            Destination destination = session.createQueue("MessageQueue");
            MessageConsumer consumer = session.createConsumer(destination);
            while (true){
                ObjectMessage message = (ObjectMessage) consumer.receive(10000);
                if(null != message){
                    String messageContent = (String) message.getObject();
                    System.out.println(messageContent);
                }else{
                    break;
                }
                message.acknowledge();
            }
            session.acknowledge();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
    public static void consumerTopic(){
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,URL);
        Connection connection = null;
        Session session = null;
        try {
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic("MessageTopic");

            MessageConsumer consumer = session.createConsumer(topic);
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    TextMessage tm = (TextMessage) message;
                    try {
                        System.out.println(tm.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
